<?php
/**
 * Created by PhpStorm.
 * User: Monkey
 * Date: 2021/10/13
 * Time: 11:27
 * Desc: 角色
 */
declare (strict_types=1);

namespace app\backend\controller;

use app\backend\base\controller\Base;
use app\backend\validate\RoleValidate;
use app\extend\model\Auth;
use think\facade\Db;

class Role extends Base
{
    /**
     * 列表
     */
    public function index()
    {
        if(request()->isPost()){
            $validate = new RoleValidate();
            $ret = $validate->scene('index')->check(input());
            if(!$ret){
                return json(_E($validate->getError()));
            }

            $page = input('page/d',1);
            $limit = input('limit/d',20);
            $fieldName = input('field_name','');
            $fieldValue = input('field_value','');

            //条件
            $where = [];

            //字段筛选
            if (!empty($fieldName) && !empty($fieldValue)) {
                switch ($fieldName) {
                    case 'role_name'://昵称
                        $where[] = ['role_name', 'like', "%{$fieldValue}%"];
                        break;
                }
            }

            $list = [];
            $count = \app\extend\model\Role::where($where)->count();
            if($count > 0){
                $list = \app\extend\model\Role::where($where)->page($page)->limit($limit)->select();
            }

            return json([
                'code' => 0,
                'msg' => '获取成功',
                'count' => $count,
                'data' => $list,
            ])->send();
        } else {
            return view('index');
        }
    }

    /**
     * 添加
     */
    public function add()
    {
        if(request()->isPost()){
            $validate = new RoleValidate();
            $ret = $validate->scene('add')->check(input());
            if(!$ret){
                return json(_E($validate->getError()));
            }

            $roleName = input('role_name','');
            $roleDesc = input('role_desc','');

            $roleInfo = \app\extend\model\Role::where([
                ['role_name','=',$roleName]
            ])->field('id')->find();
            if(!empty($roleInfo)){
                return json(_E('角色名存在'));
            }

            $result = \app\extend\model\Role::insert([
                'role_name' => $roleName,
                'role_desc' => $roleDesc,
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s')
            ]);
            if(!$result){
                return json(_E('添加失败'));
            } else {
                return json(_S('添加成功'));
            }
        }
    }

    /**
     * 修改
     */
    public function edit()
    {
        if(request()->isPost()){
            $validate = new RoleValidate();
            $ret = $validate->scene('edit')->check(input());
            if(!$ret){
                return json(_E($validate->getError()));
            }

            $id = input('id/d',0);
            $roleName = input('role_name','');
            $roleDesc = input('role_desc','');

            $roleInfo = \app\extend\model\Role::where([
                ['role_name','=',$roleName],
                ['id','<>',$id]
            ])->field('id')->find();
            if(!empty($roleInfo)){
                return json(_E('角色名存在'));
            }

            $result = \app\extend\model\Role::where([
                ['id','=',$id]
            ])->update([
                'role_name' => $roleName,
                'role_desc' => $roleDesc,
                'updated_at' => date('Y-m-d H:i:s')
            ]);
            if(!$result){
                return json(_E('修改失败'));
            } else {
                return json(_S('修改成功'));
            }
        }
    }

    /**
     * 权限
     */
    public function auth()
    {
        if(request()->isPost()){
            $validate = new RoleValidate();
            $ret = $validate->scene('auth')->check(input());
            if(!$ret){
                return json(_E($validate->getError()));
            }

            $id = input('id/d',0);
            $menuIds = input('menu_ids','');

            try {
                // 启动事务
                Db::startTrans();

                // 清空
                Auth::where([
                    ['role_id', '=', $id]
                ])->delete();

                // 添加
                if(!empty($menuIds)){
                    $saveData = array_map(function($menuIdVal) use ($id) {
                        return [
                            'role_id' => $id,
                            'menu_id' => $menuIdVal
                        ];
                    }, explode(',', $menuIds));
                    Auth::insertAll($saveData);
                }
                Db::commit();
                return json(_S('分配权限成功'));
            } catch (\Exception $e) {
                Db::rollback();
                return json(_E('分配权限失败,错误:'.$e->getMessage()));
            }
        } else {
            $roleId = input('role_id/d',0);

            //获取当前拥有的权限
            $authArr = \app\extend\model\Auth::where([
                ['role_id','=',$roleId]
            ])->field('menu_id')->select()->toArray();

            $menuIdArr = array_column($authArr,'menu_id');

            $menuArr = \app\extend\model\Menu::where([
                ['is_show','=',1]
            ])->field('id,parent_id,name,m,c,a,sort')->order(['sort' => 'asc'])->select()->toArray();

            foreach ($menuArr as &$menuVal){
                $menuVal['checked'] = false;
                if(in_array($menuVal['id'],$menuIdArr)){
                    $menuVal['checked'] = true;
                }
                $menuVal['pId'] = $menuVal['parent_id'] == 0 ? -1 : $menuVal['parent_id'];
                $menuVal['open'] = true;
            }

            return json(_S('获取成功',$menuArr));
        }
    }

    /**
     * 修改状态
     */
    public function editStatus()
    {
        if(request()->isPost()){
            $validate = new RoleValidate();
            $ret = $validate->scene('editStatus')->check(input());
            if(!$ret){
                return json(_E($validate->getError()));
            }

            $id = input('id/d',0);
            $status = input('status/d',1);

            $result = \app\extend\model\Role::where([
                ['id','=',$id]
            ])->update([
                'status' => $status,
                'updated_at' => date('Y-m-d H:i:s')
            ]);
            if(!$result){
                return json(_E('修改状态失败'));
            } else {
                return json(_S('修改状态成功'));
            }
        }
    }
}
